from __future__ import with_statement
import os
import sys
import glob
import uuid

import ts_os
import ts_qt3
import ts_vim

class private(object):
	def __init__(self):
		self.project = None
		self.output = ''
		self.output_filename = ''

def __get_project_files():
	project_files = []
	for root, dirs, files in os.walk( ts_vim.get_curdir() ):
		for s in files:
			tmp, ext = os.path.splitext(s)
			if ext.lower() == '.pro':
				project_files.append(os.path.join(root, s))
	return project_files

def __execute(command):
	return ts_os.execute2(command, __out_filter, __err_filter)

def __out_filter(line):
	__p.output += line + '\n'
	return

def __err_filter(line):
	print line
	__p.output += line + '\n'
	return

def __clear_output_lines():
	__p.output = ''
	return

def __show_output_lines():
	__p.output_filename = os.path.join(os.path.expanduser('~'), '.ts_vim.%s' 
		% str(uuid.uuid4()))
	with open(__p.output_filename, 'w') as f:
		f.write(__p.output)

	ts_vim.set_error_file(__p.output_filename)
	return

def build_select_project():
	project_files = __get_project_files()
	project_index = ts_vim.input_list('Project file', project_files)
	if project_index == -1:
		return
	p = ts_qt3.project(project_files[project_index])
	p.set_execute_function(__execute)
	p.set_execute_and_detach_function(ts_os.execute_and_detach)
	__p.project = p
	print 'Project %s selected' % p.get_file()
	return

def build_build():
	p = __p.project
	assert p, 'No project selected'
	__clear_output_lines()
	with p:
		r = p.build()
	__show_output_lines()
	assert r, 'Error building project %s' % p.get_file()
	return

def build_clean():
	p = __p.project
	assert p, 'No project selected'
	with p:
		assert p.clean(), 'Error cleaning project %s' % p.get_file()
	return

def build_create_make_file():
	p = __p.project
	assert p, 'No project selected'
	with p:
		assert p.create_make_file(), \
			'Error creating makefile for project %s' % p.get_file()
	return

def build_create_vcproject():
	p = __p.project
	assert p, 'No project selected'
	with p:
		assert p.create_vcproject(), \
			'Error creating VC project for project %s' % p.get_file()
	return

def build_run():
	p = __p.project
	assert p, 'No project selected'
	with p:
		assert p.run(), \
			'Error starting executable for project %s' % p.get_file()
	return

def build_debug():
	p = __p.project
	assert p, 'No project selected'
	with p:
		assert p.debug(), \
			'Error starting debug session for project %s' % p.get_file()
	return

def build_print_info():
	p = __p.project
	assert p, 'No project selected'
	with p:
		print p.get_env_info()
	return

def build_view_build():
	p = __p.project
	assert p, 'No project selected'
	ts_vim.edit_file(__p.output_filename)
	return

if __name__ == '__main__':
	__p = private()
